from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.db import transaction

User = get_user_model()

class Command(BaseCommand):
    help = '创建管理员用户'

    def handle(self, *args, **options):
        try:
            with transaction.atomic():
                # 检查用户是否已存在
                if User.objects.filter(username='admin').exists():
                    User.objects.filter(username='admin').delete()
                    self.stdout.write(self.style.WARNING('已删除已存在的admin用户'))

                # 创建新的管理员用户
                admin = User.objects.create_superuser(
                    username='admin',
                    password='admin',
                    email='admin@example.com',
                    mobile='13800138000'  # 添加必需的mobile字段
                )
                self.stdout.write(self.style.SUCCESS('成功创建管理员用户'))
                self.stdout.write(self.style.SUCCESS(f'用户名: {admin.username}'))
                self.stdout.write(self.style.SUCCESS('密码: admin'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'创建管理员用户失败: {str(e)}')) 